import React, { useState } from 'react'
import { Form, Input, Text, View } from 'remax/one'
import {
  cloud,
  chooseLocation,
  openSetting,
  showModal,
  showToast,
  showLoading,
  hideLoading,
} from 'remax/wechat'
import { Button, ImageUpload, Popup, Row, Col, Space, Steps } from 'annar'
import { requestCloud } from '@/hooks/use-cloud'
import useStore from '@/hooks/use-store'
import styles from './index.css'

export default ({ children }: { children?: React.ReactNode }) => {
  const { data, mutate } = useStore()
  const [user, setUser] = useState<WBG.UserInfo>()
  const [storeImgs, setStoreImgs] = useState<string[]>([])
  const [storeLocation, setStoreLocation] = useState<WBG.Location>()
  const [store, setStore] = useState<{
    name: string
    description: string
    address: string
    phoneNumber: string
  }>()
  const [licenseImgs, setLicenseImgs] = useState<string[]>([])
  const [account, setAccount] = useState<{
    sn: string
    name: string
    bank: string
  }>()
  const [status, setStatus] = useState('')
  const [reaudit, setReaudit] = useState(false)

  if (children) {
    if (data === undefined) {
      return null
    } else if (data?.audit.status === 1) {
      return <>{children}</>
    }
  }

  let step = -1
  user && (step += 1)
  store && (step += 1)
  account && (step += 1)
  status === 'error' && (step += 1)

  const getUserInfo = ({
    detail: { userInfo },
  }: {
    detail: { userInfo: WBG.UserInfo }
  }) => {
    if (userInfo) {
      const { nickName, avatarUrl, gender } = userInfo
      setUser({ nickName, avatarUrl, gender })
      setStatus('')
    } else {
      setStatus('error')
    }
  }

  const getLocation = async () => {
    try {
      const { name, address, longitude, latitude } = await chooseLocation()
      setStoreLocation({
        longitude: (longitude as unknown) as number,
        latitude: (latitude as unknown) as number,
        name,
        address,
      })
    } catch ({ errMsg }) {
      if (/auth deny/.test(errMsg)) {
        const { confirm } = await showModal({
          title: '获取位置失败',
          content: '请前往设置界面手动授权',
          showCancel: false,
        })
        confirm && (await openSetting())
        getLocation()
      }
    }
  }

  const submitStore = (values: any) => {
    let { name, description, address, phoneNumber } = values
    name = name.trim()
    description = description.trim()
    address = address.trim()
    phoneNumber = phoneNumber.trim()

    if (!name || !description || !address || !phoneNumber || !storeLocation) {
      showToast({ title: '所有内容均不能为空', icon: 'none' })
      setStatus('error')
      return
    }
    if (!storeImgs.length) {
      showToast({ title: '未上传图片', icon: 'none' })
      setStatus('error')
      return
    }

    setStatus('')
    setStore({ name, description, address, phoneNumber })
  }

  const submitAccount = async (values: any) => {
    let { sn, name, bank } = values
    sn = sn.trim()
    name = name.trim()
    bank = bank.trim()

    if (!sn || !name || !bank) {
      showToast({ title: '所有内容均不能为空', icon: 'none' })
      setStatus('error')
      return
    }
    if (!licenseImgs.length) {
      showToast({ title: '未上传图片', icon: 'none' })
      setStatus('error')
      return
    }

    setStatus('')
    setAccount({ sn, name, bank })

    try {
      showLoading({ title: '上传中', mask: true })
      const ts = Date.now()
      const getUploadPromise = (file: string, dir: string): Promise<any> => {
        const match = file.match(/\.[^\.]+$/)
        const suffix = match ? match[0].toLowerCase() : ''
        return cloud.uploadFile({
          cloudPath: `store/${dir}/${ts}${suffix}`,
          filePath: file,
        })
      }
      const res = await Promise.all([
        getUploadPromise(storeImgs[0], 'facade'),
        getUploadPromise(licenseImgs[0], 'licence'),
      ])
      hideLoading()

      let imgUrls = res.map(v => v.fileID)
      const { fileList } = await cloud.getTempFileURL({ fileList: imgUrls })
      imgUrls = fileList.map((v: any) => v.tempFileURL)
      await requestCloud('login', {
        user,
        store: {
          ...store,
          location: storeLocation,
          imgUrl: imgUrls[0],
        },
        account: {
          ...values,
          licenseImgUrl: imgUrls[1],
        },
      })
      mutate()
      setReaudit(false)
    } catch ({ errMsg }) {
      showToast({ title: '网络错误', icon: 'none' })
    }
  }

  return (
    <Popup
      open={true}
      style={{ textAlign: 'center', width: '96%', padding: 30 }}
    >
      {!data || reaudit ? (
        <Space className={styles.fullWidth} direction="vertical" size="middle">
          <Text>需要登录并完善您的门店信息</Text>
          <Steps
            current={step}
            status={status}
            steps={[
              {
                title: '个人信息',
              },
              {
                title: '门店信息',
              },
              {
                title: '账户信息',
              },
            ]}
          />
          {(() => {
            switch (step - (status === 'error' ? 1 : 0)) {
              case -1:
                return (
                  <Button
                    look="secure"
                    size="large"
                    block={true}
                    openType="getUserInfo"
                    onGetUserInfo={getUserInfo}
                  >
                    授权获取个人信息
                  </Button>
                )
              case 0:
                return (
                  <View className={styles.leftText}>
                    <Form
                      onSubmit={({ target: { value } }) => {
                        submitStore(value)
                      }}
                    >
                      <Space
                        className={styles.fullWidth}
                        direction="vertical"
                        size={20}
                      >
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              本店门脸照片
                            </Text>
                          </Col>
                          <Col flex={2}>
                            <ImageUpload
                              files={storeImgs}
                              multipleCount={1}
                              maxCount={1}
                              sizeType={['compressed']}
                              onChange={(files: any) => {
                                setStoreImgs(files)
                              }}
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>门店名称</Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="name"
                              maxLength={10}
                              placeholder="10字以内"
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>门店介绍</Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="description"
                              maxLength={20}
                              placeholder="20字以内"
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              门店文字地址
                            </Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="address"
                              maxLength={20}
                              placeholder="建议用相对学校的地址"
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              门店具体位置
                            </Text>
                          </Col>
                          <Col flex={2} className="ellipsis">
                            <Row justify="space-between" align="middle">
                              <Text className="small-text ellipsis">
                                {storeLocation?.name}
                              </Text>
                              <Button onTap={getLocation}>地图选址</Button>
                            </Row>
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              门店联系电话
                            </Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="phoneNumber"
                              type="number"
                              maxLength={20}
                            />
                          </Col>
                        </Row>
                        <Button
                          look="secure"
                          size="large"
                          block={true}
                          formType="submit"
                        >
                          确认门店信息
                        </Button>
                      </Space>
                    </Form>
                  </View>
                )
              case 1:
              case 2:
                return (
                  <View className={styles.leftText}>
                    <Form
                      onSubmit={({ target: { value } }) => {
                        submitAccount(value)
                      }}
                    >
                      <Space
                        className={styles.fullWidth}
                        direction="vertical"
                        size={20}
                      >
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              营业执照或副本照片
                            </Text>
                          </Col>
                          <Col flex={2}>
                            <ImageUpload
                              files={licenseImgs}
                              multipleCount={1}
                              maxCount={1}
                              sizeType={['compressed']}
                              onChange={(files: any) => {
                                setLicenseImgs(files)
                              }}
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>收款账户</Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="sn"
                              maxLength={30}
                              placeholder="收取客户消费的银行账户"
                            />
                          </Col>
                        </Row>
                        <Row>
                          <Col flex={1}></Col>
                          <Col flex={2}>
                            <View className={styles.tipText}>
                              具体转账规则参考《蜗大郎商户合作协议》。
                            </View>
                            <View className={styles.tipText}>
                              必须是营业执照照片的企业的对公账户，或者企业法人的私人账户。
                            </View>
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>
                              收款账户名称
                            </Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="name"
                              maxLength={20}
                              placeholder="账户户主的名称"
                            />
                          </Col>
                        </Row>
                        <Row align="middle">
                          <Col flex={1}>
                            <Text className={styles.labelText}>账户开户行</Text>
                          </Col>
                          <Col flex={2}>
                            <Input
                              className={styles.input}
                              name="bank"
                              maxLength={20}
                              placeholder="可通过银行客服热线查询"
                            />
                          </Col>
                        </Row>
                        <Button
                          look="secure"
                          size="large"
                          block={true}
                          formType="submit"
                        >
                          确认账户信息并提交审核
                        </Button>
                      </Space>
                    </Form>
                  </View>
                )
            }
          })()}
        </Space>
      ) : data.audit.status === 0 ? (
        <Space className={styles.fullWidth} direction="vertical" size="middle">
          <Text>您的门店信息正在审核中</Text>
          <Button
            look="secure"
            size="large"
            block={true}
            onTap={async () => {
              mutate()
              showToast({ title: '已收到，会为您尽快审核', icon: 'none' })
            }}
          >
            催一催
          </Button>
        </Space>
      ) : data.audit.status === 2 ? (
        <Space className={styles.fullWidth} direction="vertical" size="middle">
          <Text>您的门店信息审核未通过</Text>
          <Text className={styles.tipText}>{data.audit?.reason}</Text>
          <Button
            look="secure"
            size="large"
            block={true}
            onTap={() => {
              setReaudit(true)
            }}
          >
            修改并重新审核
          </Button>
        </Space>
      ) : null}
    </Popup>
  )
}
